package com.youu.youu.restapi.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.youu.youu.manager.bean.TUser;
import com.youu.youu.manager.bean.UserLocationData;
import com.youu.youu.restapi.service.UserService;


/*
 * 个人中心请求处理
 */
@RestController
@RequestMapping("/usermain")
public class UserMainController {
	
	@Autowired
	UserService userService;
	
	public String[] getUserLocationFile(HttpServletRequest request,String loginacct){
		StringBuilder sb = new StringBuilder();
		String fileaddress = "";
		String fileName = "";
		
		if("".equals(loginacct)){
			//用户为空，显示默认位置
			System.out.println("用户为空");
			
			fileaddress ="/admin/admin.txt";
			
			//1.获取某个文件夹在服务器上的真实路径
	        ServletContext context = request.getSession().getServletContext();
	        //2.使用context对象获取真实路径
	        String adPath = context.getRealPath("/personalFile");
	        System.out.println("默认文件位置:"+adPath);
	        
	       
	        fileName = adPath+fileaddress;
	        
		}else{
			
			
			fileaddress = "/"+loginacct+"/"+loginacct+"_LocationFile.txt";
			
			//1.获取某个文件夹在服务器上的真实路径
	        ServletContext context = request.getSession().getServletContext();
	        //2.使用context对象获取真实路径
	        String adPath = context.getRealPath("/personalFile");
			
			//通过用户名查询文件位置
			fileName = adPath+fileaddress;
		}
		
		
		
		
		
		
        byte[] buf=new byte[1024];  
        int len=0;  
        FileInputStream fInputStream = null;
		try {
			fInputStream = new FileInputStream(fileName);  
			while((len=fInputStream.read(buf))!=-1)  
			{  
				sb.append(new String(buf,0,len,"UTF-8"));
			}
			System.out.println("文件："+fileName+" 中的内容是:\n"+sb);
		}catch (IOException e1) {
			e1.printStackTrace();
		}  finally {
			//关闭流
			try {
				if(fInputStream!=null){
					fInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
        
		String[] split = sb.toString().split("-");
		
		return split;
        
		/*try {
            String encoding="UTF";
            File file = new File(fileaddress);
            System.out.println(file.getName());
            
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                }
                read.close();
	    }else{
	        System.out.println("找不到指定的文件");
	    }
	    } catch (Exception e) {
	        System.out.println("读取文件内容出错");
	        e.printStackTrace();
	    }*/
		
		
	}
	
	
	@ResponseBody
    @RequestMapping(value="/data.json", produces = "application/json; charset=utf-8")
    public List<UserLocationData> data(@RequestParam("loginacct")String loginacct,HttpServletResponse response,HttpServletRequest request) {
        System.out.println("data.json");
        
        List<UserLocationData> dataList = new ArrayList<>();
        
        String[] location = getUserLocationFile(request,loginacct);
		
        if("".equals(location[0])&&location.length==1){
			return dataList;
		}
        
		for(int i=1;i<location.length;i++){
			
			String[] split = location[i].split(",");
			dataList.add(new UserLocationData(split[2], Integer.parseInt(split[3])));
			
		}
		
        
        /*dataList.add(new UserLocationData("秦皇岛", 250));
        dataList.add(new UserLocationData("石家庄", 252));*/
        
        return dataList;
                //"[{name: '海门', value: 80},{name: '鄂尔多斯', value: 80},{name: '招远', value: 80},{name: '舟山', value: 80},{name: '齐齐哈尔', value: 80},{name: '日照', value: 250},{name: '秦皇岛', value: 250}, {name: '石家庄hahaha', value: 252}]";
    }
    
    @ResponseBody
    @RequestMapping(value="/geoCoordMap.json", produces = "application/json; charset=utf-8")
    public Map<String, double[]> geoCoordMap(@RequestParam("loginacct")String loginacct,HttpServletRequest request){
        System.out.println("geoCoordMap.json");
        
        Map<String, double[]> geoMap = new HashMap<String, double[]>();
        
        String[] location = getUserLocationFile(request,loginacct);
        
        if("".equals(location[0])&&location.length==1){
			return geoMap;
		}
        
        
        for(int i=1;i<location.length;i++){
        	String[] split = location[i].split(",");
        	geoMap.put(split[2],new double[]{Double.parseDouble(split[0]),Double.parseDouble(split[1])});
        }
        
        
        
        /*geoMap.put("秦皇岛",new double[]{119.57,39.95});
        geoMap.put("招远",new double[]{120.38,37.35});
        geoMap.put("舟山",new double[]{122.207216,29.985295});
        geoMap.put("日照",new double[]{119.46,35.42});
        geoMap.put("石家庄",new double[]{114.48,38.03});*/
        return geoMap;
                //"{\"秦皇岛\":[119.57,39.95],\"石家庄hahaha\":[114.48,38.03]}";
                //"{'海门':[121.15,31.89],'鄂尔多斯':[109.781327,39.608266],'招远':[120.38,37.35],'舟山':[122.207216,29.985295],'齐齐哈尔':[123.97,47.33],'日照':[119.46,35.42],'秦皇岛':[119.57,39.95],'石家庄hahaha':[114.48,38.03]}";
    }
    
    @ResponseBody
    @RequestMapping("/userGender")
    public String userGender(@RequestParam("gender")String gender,@RequestParam("uid")Integer uid){
    	//插入用户性别
    	System.out.println("用户id:"+uid);
    	TUser user = new TUser();
    	user.setGender(Integer.parseInt(gender));
    	user.setId(uid);
    	userService.upDateByUser(user);
    	return ""+gender;
    }
	
}
